﻿using Mangdot.Webchat.Common;
using Mangdot.Webchat.Data;
using Mangdot.Webchat.Models;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Mangdot.Webchat.Controllers
{
    public class AdminController : Controller
    {
        // GET: Admin
        public ActionResult Index()
        {
            using (var context = new Data.HeKaEntities())
            {
                var query = (from item in context.Template
                             join c in context.Categroy on item.CategoryId equals c.Id
                             select new Models.TemplateModel
                             {
                                 Id = item.Id,
                                 Category = c.Name,
                                 Name = item.Name,
                                 CreateTime = item.CreateTime
                             }).OrderByDescending(x => x.CreateTime).ToArray();

                return View(query);
            }
        }

        public ActionResult Cards()
        {
            using (var context = new Data.HeKaEntities())
            {
                var query = (from item in context.Cards
                             select new Models.CardsModel
                             {
                                 Id = item.Id,
                                 CardType = item.CardType,
                                 Title = item.Title,
                                 Img = item.Img,
                                 Content = item.Content,
                                 Audio = item.Audio,
                                 VisitUrl = item.VisitUrl,
                                 CreateTime = item.CreateTime
                             }).OrderByDescending(x => x.CreateTime).ToArray();

                return View(query);
            }
        }


        public JsonResult GetCategory()
        {
            using (var context = new HeKaEntities())
            {
                var query = (from item in context.Categroy
                             select new
                             {
                                 Id = item.Id,
                                 Name = item.Name
                             }).ToList();

                return Json(query);
            }
        }

        public JsonResult GetTemplateList()
        {
            using (var context = new HeKaEntities())
            {
                var query = (from item in context.Template
                             select new
                             {
                                 Id = item.Id,
                                 Name = item.Name
                             }).ToList();

                return Json(query);
            }
        }

        public JsonResult GetTemplate(int id)
        {
            using (var context = new HeKaEntities())
            {
                var query = (from item in context.Template
                             where item.Id == id
                             select item).FirstOrDefault();

                return Json(query);
            }
        }

        public JsonResult GetCard(int id)
        {
            using (var context = new HeKaEntities())
            {
                var query = (from item in context.Cards
                             where item.Id == id
                             select item).FirstOrDefault();

                return Json(query);
            }
        }

        [ValidateInput(false)]
        public JsonResult SaveTemplate(Models.TemplateModel model)
        {
            using (var context = new HeKaEntities())
            {
                if (model.Id > 0)
                {
                    var query = (from item in context.Template
                                 where item.Id == model.Id
                                 select item).FirstOrDefault();

                    if (query != null)
                    {
                        query.Name = model.Name;
                        query.CategoryId = model.CategoryId;
                        query.Content = model.Content;

                        var count = context.SaveChanges();

                        return Json(count > 0);
                    }
                }
                else
                {
                    context.Template.Add(new Data.Template
                    {
                        Name = model.Name,
                        CategoryId = model.CategoryId,
                        Content = model.Content,
                        CreateTime = DateTime.Now
                    });

                    var count = context.SaveChanges();
                    return Json(count > 0);
                }

                return Json(false);
            }
        }

        public JsonResult SaveCard(Models.CardsModel model)
        {
            using (var context = new HeKaEntities())
            {
                if (model.Id > 0)
                {
                    var query = (from item in context.Cards
                                 where item.Id == model.Id
                                 select item).FirstOrDefault();

                    if (query != null)
                    {
                        query.Title = model.Title;
                        query.TemplateId = model.TemplateId;
                        query.Content = model.Content;
                        query.Audio = model.Audio;
                        query.Img = model.Img;
                        var count = context.SaveChanges();

                        return Json(count > 0);
                    }
                }
                else
                {
                    context.Cards.Add(new Data.Cards
                    {
                        CardType = "Default",
                        Title = model.Title,
                        TemplateId = model.TemplateId,
                        Content = model.Content,
                        Img = model.Img,
                        Audio = model.Audio,
                        CreateTime = DateTime.Now,
                        VisitUrl = ""
                    });

                    var count = context.SaveChanges();
                    return Json(count > 0);
                }

                return Json(false);
            }
        }

        public JsonResult GeneralSite(int id)
        {
            using (var context = new HeKaEntities())
            {
                var query = (from item in context.Template
                             where item.Id == id
                             select item).FirstOrDefault();

                if (query != null)
                {
                    string path = string.Format("{0}/HEKA/{1}", AppDomain.CurrentDomain.BaseDirectory, query.Name);

                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }

                    return Json(true);
                }

                return Json(false);
            }
        }


        public JsonResult Publish(int id)
        {
            using (var context = new HeKaEntities())
            {
                var query = (from item in context.Cards
                             join t in context.Template on item.TemplateId equals t.Id
                             where item.Id == id
                             select new
                             {
                                 tName = t.Name,
                                 tContent = t.Content,
                                 iTitle = item.Title,
                                 iContent = item.Content,
                                 iAudio = item.Audio,
                                 iImg = item.Img,
                                 VisitUrl = item.VisitUrl
                             }).FirstOrDefault();

                if (query != null)
                {
                    string path = string.Format("{0}/HEKA/{1}", AppDomain.CurrentDomain.BaseDirectory, query.tName);



                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }

                    string fileName = string.Format("/HEKA/{0}/{1}.html", query.tName, DateTime.Now.ToString("yyyy-MM-dd-HHmmss"));

                    RazorHelper.CompileHtml(query.tContent, new Models.HKModel
                    {
                        Title = query.iTitle,
                        ScrollTxt = query.iContent,
                        BackgroundImg = query.iImg,
                        BackgroundMusic = query.iAudio,
                        FileName = fileName
                    }, path, fileName);

                    if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + query.VisitUrl))
                    {
                        //删除原来文件
                        System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + query.VisitUrl);
                    }

                    var card = (from item in context.Cards
                                where item.Id == id
                                select item).FirstOrDefault();

                    if (card != null)
                    {
                        card.VisitUrl = fileName;
                        var isOk = context.SaveChanges() > 0;
                        return Json(isOk);
                    }
                }

                return Json(false);
            }
        }

        public JsonResult PublishHome()
        {
            using (var context = new HeKaEntities())
            {
                var query = (from item in context.Cards
                             where item.CardType == "Default"
                             select new CardsModel
                             {
                                 Id = item.Id,
                                 Title = item.Title,
                                 Img = item.Img,
                                 VisitUrl = item.VisitUrl,
                                 CreateTime = item.CreateTime
                             }).OrderByDescending(x => x.CreateTime).ToList();

                var t = (from item in context.Template
                         join c in context.Categroy on item.CategoryId equals c.Id
                         where c.Name == "Home"
                         select item).FirstOrDefault();

                var title = new RazorEngine.Templating.DynamicViewBag();
                title.AddValue("Title", t.Name);
                Common.RazorHelper.CompileHtml(t.Content, query, title);

                return Json(true);
            }
        }
    }
}